<?php
namespace App\Http\Controllers\Api;

use App\V3\V3_1\Models\AdminModel;
use App\V3\V3_1\Models\AuthMenuModel;
use App\V3\V3_1\Models\CheckModel;
use App\V3\V3_1\Models\ModuleModel;
use App\V3\V3_1\Models\OverflowBreakageChecksModel;
use App\V3\V3_1\Models\OverflowBreakageDetailModel;
use App\V3\V3_1\Models\OverflowBreakageModel;
use App\Services\OutInRepealService;
use App\Services\StorageManageService;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * 审批
 * Class CheckController
 * @package App\Http\Controllers\Api
 */
class CheckController extends BaseController
{
    /**
     * 审批列表
     * change 在 2021/11/9 16:32 创建
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
            'type'=>'required|integer'//类型：0-报溢报损 1-销售采购
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        if($data['type']==0){
            $type = [0,1];
        }else{
            $type = [2,3];
        }
        if($this->getMainUserId() == $this->getUserId()){//超管
            $model = CheckModel::select('a.*','b.username')
                ->from('check as a')
                ->leftJoin('admin as b','a.user_id', '=','b.id')
                ->where('status',0)
                ->where('a.repeal_status',0)
                ->where('a.main_id',$this->getMainUserId())
                ->whereIn('type',$type)
                ->orderBy('a.id','desc')
                ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        }else{
            $userId = $this->getUserId();
            if($data['type']==0){//报溢报损
                $model = CheckModel::select('a.*','b.username')
                    ->from('check as a')
                    ->leftJoin('admin as b','a.user_id', '=','b.id')
                    ->where('status',0)
                    ->whereIn('type',$type)
                    ->orderBy('a.id','desc')
                    ->where('a.repeal_status',0)
                    ->where('a.main_id',$this->getMainUserId())
                    ->whereRaw("FIND_IN_SET($userId,`check_person`)")
                    ->whereRaw("FIND_IN_SET($userId,`check_person_tmp`)")
                    ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
            }else{//销售采购
//                $authMenu = ModuleModel::where('module_name','审批')->where('delete_flag', 0)->value('id');
//                $auth = AdminModel::where('id',$userId)->whereRaw("FIND_IN_SET($authMenu,`first_module`)")->first();
//                if(!$auth){
//                    return $this->fail('','请联系管理员添加审批权限');
//                }
                $model = CheckModel::select('a.*','b.username')
                    ->from('check as a')
                    ->leftJoin('admin as b','a.user_id', '=','b.id')
                    ->where('status',0)
                    ->whereIn('type',$type)
                    ->where('a.repeal_status',0)
                    ->where('a.main_id',$this->getMainUserId())
                    ->orderBy('a.id','desc')
                    ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
            }

        }
        return $this->success($model);
    }

    /**
     * 报溢报损同意或拒绝
     * change 在 2021/11/9 16:33 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function agreeOrRefund(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//审批主键id
            'all_id' =>'required|integer',//关联id
            'status' =>'required|string',//审批状态：0-拒绝 1-同意
            'remark' =>'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //开启事务
        DB::beginTransaction();
        try{
            $overflowBreakageChecksModel = OverflowBreakageChecksModel::where(['o_b_main_id'=>$data['all_id'],'admin_id'=>$this->getUserId()])->first();
            if($data['status']==1){
                //更新审核人审核状态
                $overflowBreakageChecksModel->status = 1;
                $overflowBreakageChecksModel->save();
                $all = OverflowBreakageChecksModel::where(['o_b_main_id'=>$data['all_id']])->count();
                $agree = OverflowBreakageChecksModel::where(['status'=>1,'o_b_main_id'=>$data['all_id']])->count();
                $refund = OverflowBreakageChecksModel::where(['status'=>2,'o_b_main_id'=>$data['all_id']])->count();
                if($all==$agree){//全部通过入库
                    OverflowBreakageModel::where('id',$data['all_id'])->update(['status'=>1]);//更新报溢报损审核状态
                    CheckModel::where('id',$data['id'])->update(['status'=>1]);//审批状态更新
                    //出入库参数
                    $paramsArr = [];//出入库参数
                    $paramsArr['all_id'] = $data['all_id'];
                    $paramsArr['remark'] = '';
                    $paramsArr['all_id_type'] = 1;//报溢报损均为1
                    $OverflowBreakageDetailModel = OverflowBreakageDetailModel::where('o_b_main_id',$data['all_id'])->get();
                    foreach ($OverflowBreakageDetailModel as $k=>$val){
                        $paramsArr['content'][$k]['name'] = $val['name'];
                        $paramsArr['content'][$k]['price'] = 0;
                        $paramsArr['content'][$k]['type_name'] = $val['type_name'];
                        $paramsArr['content'][$k]['num'] = $val['num'];
                        $paramsArr['content'][$k]['warehouse'] = $val['warehouse'];
                        $paramsArr['content'][$k]['warehouse_id'] = $val['warehouse_id'];
                    }
                    $checkModel = CheckModel::find($data['id']);
                    if($checkModel->type==0){//报溢入库
                        $paramsArr['in_storage_time'] = date('Y-m-d H:i:s');
                        $res = StorageManageService::inStorage($this->getUserId(), $this->getMainUserId(), $paramsArr);
                        if($res['code']){
                            return $this->fail('',$res['msg']);
                        }

                    }else{//报损出库
                        $paramsArr['out_storage_time'] = date('Y-m-d H:i:s');
                        $res = StorageManageService::outStorage($this->getUserId(), $this->getMainUserId(), $paramsArr);
                        if($res['code']){
                            return $this->fail('',$res['msg']);
                        }
                    }
                }
                if($all==($agree+$refund) && $refund){//部分拒绝
                    OverflowBreakageModel::where('id',$data['all_id'])->update(['status'=>2]);//更新报溢报损审核状态
                    CheckModel::where('id',$data['id'])->update(['status'=>1]);//审批状态更新
                }
            }else{//拒绝
                //更新审核人审核状态
                $overflowBreakageChecksModel->status = 2;
                $overflowBreakageChecksModel->refund_remark = isset($data['remark'])?$data['remark']:"";
                $overflowBreakageChecksModel->save();
                $obc = OverflowBreakageChecksModel::where(['status'=>0,'o_b_main_id'=>$data['all_id']])->first();
                if(!$obc){
                    OverflowBreakageModel::where('id',$data['all_id'])->update(['status'=>2]);//更新报溢报损审核状态
                    CheckModel::where('id',$data['id'])->update(['status'=>1]);//审批状态更新
                }
            }
            //更新临时审批人
            $model = CheckModel::where('id',$data['id'])->first();
            if($model['check_person_tmp']){
                $arr = explode(',',$model['check_person_tmp']);
                $userIdIndex = array_search($this->getUserId(),$arr);
                unset($arr[$userIdIndex]);
                $model->check_person_tmp = implode(',',$arr);
                $model->save();
            }
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'审核报溢或报损失败');
        }
    }

    /**
     * 销售出库
     * change 在 2021/11/9 16:33 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function out(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//审批主键id
            'status' => 'required|integer',//出入库状态：0-部分 1-全部
            'goods_info' => 'string',//商品信息  array
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        //开启事务
//        DB::beginTransaction();
//        try{
        $checkModel = CheckModel::find($data['id']);
            if($data['status']==0){//部分
                $res = OutInRepealService::outIn(1,$checkModel['all_id'],1,$data['goods_info']);//出库处理
                $checkModel->out_in_status = 1;
                $checkModel->save();
                if($res==1){
                    return $this->fail('数量不符无法入库');
                }elseif ($res==3){
                    $checkModel->status = 1;
                    $checkModel->out_in_status = 0;
                    $checkModel->save();
                }
            }else{//全部
                //审核状态更新
                $checkModel->status = 1;
                $checkModel->out_in_status = 0;
                $checkModel->save();
                OutInRepealService::outIn(1,$checkModel['all_id'],2);//出库处理
            }
            DB::commit();//提交事务
            return $this->success();
//        }catch (Exception $e){
//            DB::rollBack();//事务回滚
//            //异常响应
//            return $this->fail($e->getMessage(),'出库异常');
//        }
    }
}
